<?php
namespace app\common\model;
use think\Db;
/**
 * 订单退款模型
 */
class OrderRefund extends Base {
	protected $pk = 'refundId';
	/**
	 * 用户申请退款
	 */
	public function refund($uId = 0)
	{
		$orderId = (int)input('post.id');
		$reason = (int)input('post.reason');
		$content = input('post.content');
		$money = (float)input('post.money');
		$userId = ($uId == 0) ? (int)session('ZHT_USER.userId') : $uId;
		if ($money < 0) return ZHTReturn("退款金额不能为负数");
		$order = Db::name('order')->alias('o')->join('__ORDER_REFUND__ orf', 'orf.orderId=o.orderId', 'left')->join('__SHOP__ s', 'o.shopId=s.shopId', 'left')
		->where([['o.orderStatus', 'in', [-3, -1]], ['o.orderId', '=', $orderId], ['o.userId', '=', $userId], ['o.isRefund', '=', 0]])
			->field('o.orderId,s.userId,o.shopId,o.orderStatus,o.orderNo,o.realTotalMoney,o.isPay,o.payType,o.useScore,orf.refundId')->find();
		$reasonData = ZHTData(10, $reason);
		if (empty($reasonData)) return ZHTReturn("无效的退款原因");
		if ($reason == 10000 && $content == '') return ZHTReturn("请输入退款原因");
		if (empty($order)) return ZHTReturn('操作失败，请检查订单是否符合申请退款条件');
		$allowRequest = false;
		if ($order['isPay'] == 1 || $order['useScore'] > 0) {
			$allowRequest = true;
		}
		if (!$allowRequest) return ZHTReturn("您的退款申请已提交，请留意退款信息");
		if ($money > $order['realTotalMoney']) return ZHTReturn("申请退款金额不能大于实支付金额");
		//查看退款申请是否已存在
		$orfId = $this->where('orderId', $orderId)->value('refundId');
		Db::startTrans();
		try {
			$result = false;
			//如果退款单存在就进行编辑
			if ($orfId > 0) {
				$object = $this->get($orfId);
				$object->refundReson = $reason;
				if ($reason == 10000) $object->refundOtherReson = $content;
				$object->backMoney = $money;
				$object->refundStatus = 0;
				$result = $object->save();
			} else {
				$data = [];
				$data['orderId'] = $orderId;
				$data['refundTo'] = 0;
				$data['refundReson'] = $reason;
				if ($reason == 10000) $data['refundOtherReson'] = $content;
				$data['backMoney'] = $money;
				$data['createTime'] = date('Y-m-d H:i:s');
				$data['refundStatus'] = 0;
				$result = $this->save($data);
			}
			if (false !== $result) {
				Db::commit();
				return ZHTReturn('您的退款申请已提交，请留意退款信息', 1);
			}
		} catch (\Exception $e) {
			Db::rollback();
		}
		return ZHTReturn('操作失败', -1);
	}
}